package com.healthai.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Component
public class AiUtil {
    
    @Value("${dashscope.api-key}")
    private String apiKey;
    
    @Value("${dashscope.app-id}")
    private String appId;
    
    @Value("${dashscope.base-url}")
    private String baseUrl;
    
    private final WebClient webClient;
    private final ObjectMapper objectMapper;
    
    public AiUtil() {
        this.webClient = WebClient.builder()
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();
        this.objectMapper = new ObjectMapper();
    }
    
    /**
     * 调用百炼AI获取健康建议
     * @param prompt 用户健康数据提示
     * @return AI建议
     */
    public Mono<String> getHealthAdvice(String prompt) {
        String url = baseUrl + "/" + appId + "/completion";
        
        Map<String, Object> requestBody = new HashMap<>();
        Map<String, Object> input = new HashMap<>();
        input.put("prompt", prompt);
        requestBody.put("input", input);
        requestBody.put("parameters", new HashMap<>());
        requestBody.put("debug", new HashMap<>());
        
        return webClient.post()
                .uri(url)
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(String.class)
                .flatMap(this::extractAiResponse);
    }
    
    /**
     * 从AI响应中提取文本内容
     * @param response AI响应
     * @return 提取的文本内容
     */
    private Mono<String> extractAiResponse(String response) {
        try {
            JsonNode rootNode = objectMapper.readTree(response);
            if (rootNode.has("output") && rootNode.get("output").has("text")) {
                return Mono.just(rootNode.get("output").get("text").asText());
            }
            return Mono.just("抱歉，暂时无法获取AI建议，请稍后再试。");
        } catch (Exception e) {
            return Mono.just("解析AI响应时出错：" + e.getMessage());
        }
    }
}